<template>
  <a-modal
    title="修改密码"
    width="45%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    destroyOnClose
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="原密码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入旧密码"
            v-decorator="['oldPassword', {
              rules: [{required: true, message: '请输入正确的旧密码'}]}]"
          />
        </a-form-item>
        <a-form-item
          label="新密码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入新密码"
            v-decorator="['newPassword', {
              rules: [{required: true, message: '请输入正确格式的新密码'}]}]"
          />
        </a-form-item>
        <a-form-item
          label="确认新密码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请再次输入新密码"
            v-decorator="['confirmNewPassword', {
              rules: [{required: true, validator: handleConfirmPassword, message: '请再次输入正确格式的新密码'}]}]"
          />
        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { updatePassword } from '@/api/login'
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      form: this.$form.createForm(this),
      visible: false,
      confirmLoading: false
    }
  },
  methods: {

    ...mapActions(['Logout']),
    handleConfirmPassword(rule, value, callback) {
      const { getFieldValue } = this.form
      if (value && value !== getFieldValue('newPassword')) {
        callback(new Error('两次输入的密码不一致！'))
      } else {
        callback()
      }
    },
    handleSubmit() {
      this.confirmLoading = true
      this.form.validateFields((errors, values) => {
        if (!errors) {
          updatePassword(values)
            .then(() => {
              this.handleCancel()
              this.$message.success('修改密码成功')
              return this.Logout({}).then(() => {
                window.location.reload()
              })
            })
            .finally(() => { this.confirmLoading = false })
        } else {
          this.confirmLoading = false
        }
      })
    },
    show() {
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>
